<?php

class CacheService extends Service_Base
{
	private static $_instance;
	
	public static function getInstance()
	{
		if (!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}	
	/**
	 * Get select from cache or execute query and add the result to cache
	 *
	 * @param Db_Peer $peer
	 * @param Db_Select $select
	 * @param unknown_type $cacheTime
	 * @param Cache_Tag_Abstract $tag
	 * @param boolean $reset
	 * @return Db_Rowset
	 */
	public function getCachedSelect(Db_Peer $peer, Db_Select $select = null, $cacheTime = 3600, Cache_Tag_Abstract $tag = null, $reset = false)
	{
		if(!$select) $select = $peer->select();
		$cacheslot = new Cache_Slot_Query($select, $cacheTime);
		$data = $cacheslot->load();
		if ($data && !$reset) {
			$contentRowset = $data;
			try {	
				$contentRowset->setTable($peer);
			} catch (Exception $e) {}
		} else {
			$contentRowset = $peer->fetchAll($select);
			if ($tag) {
				$cacheslot->addTag($tag);
			}
			$cacheslot->save($contentRowset);
		}
		
		return $contentRowset;
	}
}